import DetailContainer, { Title } from "@/components/DetailContainer";
import { addUser, editUser, getUserDetail } from "@/services/user";
import type { ProFormInstance } from "@ant-design/pro-components";
import { ProForm, ProFormText } from "@ant-design/pro-components";
import { history, useParams } from "@umijs/max";
import { Form, message } from "antd";
import { cloneDeep } from "lodash";
import { useRef } from "react";

const queryMap = {
  add: addUser,
  update: editUser
};

const UseUserAddEdit = () => {
  const [form] = Form.useForm();
  const { id } = useParams();
  const isNew = id === "new";
  const formRef = useRef<ProFormInstance<any>>();

  return (
    <DetailContainer>
      <ProForm
        form={form}
        formRef={formRef}
        request={async () => {
          if (isNew) return {};
          let params = {
            id: id as string
          };
          let resp = await getUserDetail(params);
          if (resp.code === 1) {
            return {
              ...resp.data
            };
          }
          return {};
        }}
        onFinish={async () => {
          const values = cloneDeep(form.getFieldsValue(true));
          const resp = await queryMap[isNew ? "add" : "update"](values);
          if (resp?.code === 1) {
            history.push("/users/list");
            message.success(`${isNew ? "新增" : "编辑"}用户成功`);
          }
        }}
      >
        <Title>基本信息</Title>
        <ProFormText
          label="姓名"
          rules={[{ required: true, message: "此项必填" }]}
          name="name"
          width="sm"
        />
      </ProForm>
    </DetailContainer>
  );
};

export default UseUserAddEdit;
